package com.fxhy.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baby.bean.SysConfig;
import com.baby.bean.UserInfo;
import com.baby.constants.Constants;
import com.baby.contants.MyConstant;
import com.baby.myutils.CosUtil;
import com.baby.utils.CommonUtils;
import com.baby.utils.DateUtils;
import com.fxhy.bean.AgentUser;
import com.fxhy.bean.custom.AgentUserCustom;
import com.fxhy.mapper.SysConfigMapper;
import com.fxhy.mapper.UserMapper;
import com.fxhy.repository.UserInfoRepository;
import com.fxhy.utils.Beanutils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserService {
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private SysConfigMapper sysConfigMapper;
	
	
	/**
	 * 管理端条件查询用户列表
	 * @param pageInfo
	 * @param nickName 昵称-查询
	 * @param isHavePhone 是否绑定号码
	 * @param isHaveWechat 是否绑定微信
	 * @param shared 邀请状态
	 * @param loginStatus 登录状态
	 * @return
	 */
	public PageInfo<AgentUser> findUserListByMap(PageInfo<AgentUser> pageInfo, String nickName,Integer status, String isHavePhone, 
			String isHaveWechat, Integer shared, Integer loginStatus) {
		Map<String,Object> map = new HashMap<String,Object>();
//		if(map.get("orderBy") != null && !map.get("orderBy").equals("")){
//			orderBy = (String) map.get("orderBy");
//		}
		if(isHavePhone == null || isHavePhone.equals("") || isHavePhone.equals("all")){
			isHavePhone = null;
		}
		if(isHaveWechat == null || isHaveWechat.equals("") || isHaveWechat.equals("all")){
			isHaveWechat = null;
		}

		//登录状态
		map.put("loginStatus", loginStatus);
		
		map.put("isHavePhone", isHavePhone);
		map.put("isHaveWechat", isHaveWechat);
		map.put("nickName", nickName);
		map.put("status", status);
		map.put("isShared", shared);
		PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize(),pageInfo.getOrderBy());
		List<AgentUser> list = userMapper.findUserListByMap(map);
		return new PageInfo<AgentUser>(list);
	}

	public AgentUser updateUser(AgentUser userInfo){
		AgentUser old = userInfoRepository.findByUserId(userInfo.getUserId());
		try {
			Beanutils.merge(userInfo, old);
		} catch (Exception e) {
			log.error("合并UserInfo bean失败.....");
			return null;
		}
		return userInfoRepository.saveAndFlush(userInfo);
	}

	public AgentUser findById(Integer uid) {
		return userInfoRepository.findByUserId(uid);
	}

	public AgentUser findUserByPhone(String phone) {
		AgentUser userInfo = new AgentUser();
		List<AgentUser> userInfos = userInfoRepository.findByPhoneNum(phone);
		if(userInfos!=null && userInfos.size()>0){
			userInfo = userInfos.get(0);
		}
		return userInfo;
	}
	
	
	/**
	 * 根据手机号注册用户信息
	 * @param phone
	 * @param deviceType 
	 * @param sharedByUserId 
	 * @return
	 */
	public AgentUser registerUserByPhone(String phoneNum) {
		
		AgentUser userInfo = new AgentUser();

		userInfo.setNickName(getNickName(phoneNum));  //昵称
		userInfo.setSex(-1);                       //性别       默认为-1
		userInfo.setHeadImgUrl(MyConstant.DEFAULT_HEAD);  //默认头像
		
		userInfo.setMemberType(1);                        //默认普通员工
		userInfo.setIsOnline(0);                          //默认不在线
		userInfo.setLastLoginTime(DateUtils.getNowDate());//最后登录时间
		
		userInfo.setUserAccount(phoneNum);		   //用户账号
		userInfo.setPhoneNum(phoneNum);			   //手机号
		userInfo.setSecurityCode("");			   //手机验证码
		
		userInfo.setRoleId(-1);
		userInfo.setIsBindingCard(0);
		userInfo.setIsBindingBank(0);
		userInfo.setIsBindingLicence(0);
		userInfo.setIsIdentifi(-1);
		
		userInfo.setStatus(1);
		userInfo.setCreateTime(DateUtils.getNowDate());
		userInfo.setCreateUser(phoneNum);
		userInfo.setUpdateTime(DateUtils.getNowDate());
		userInfo.setUpdateUser(phoneNum);
		
		userInfo = userInfoRepository.saveAndFlush(userInfo);
		return userInfo;
	}
	
	/**
	 * 根据手机号注册娃娃用户
	 * @param phone
	 * @return
	 */
	public UserInfo registerUserByPhone(String phone,Integer sharedByUserId) {
		
		SysConfig sysConfig = new SysConfig();
		sysConfig.setBgsoundSwitch(Constants.BG_SOUNDSWITCH_ON);
		sysConfig.setSoundEffectSwitch(Constants.SOUND_EFFECTSWITCH_ON);//音效开关
		sysConfig.setCallAutoPalySwitch(Constants.CALL_AUTOPALYSWITCH_ON);//聊天语音自动播放开关
		sysConfig.setShakeHintSwitch(Constants.SHAKE_HINTSWITCH_ON);//震动提示
		sysConfig.setReceiveFriendSwitch(Constants.RECEIVE_FRIENDSWITCH_ON);//接收好友请求
		sysConfig.setCreateTime(DateUtils.getNowDate());
		sysConfig.setCreateUser(Constants.SYS_CREATEUSER);
		sysConfig.setUpdateTime(DateUtils.getNowDate());
		sysConfig.setUpdateUser(Constants.SYS_CREATEUSER);
		int sysId = sysConfigMapper.insertSysConfig(sysConfig);
		
		UserInfo userInfo = new UserInfo();
		userInfo.setBalance(0);
		userInfo.setSysConfigId(sysId);//系统设置Id
		userInfo.setUserName(getNickName(phone));//用户名
		userInfo.setUserAccount(phone);//用户账号
		userInfo.setPassword("123456");//密码
		userInfo.setPhone(phone);//手机号
		userInfo.setSecurityCode("");//手机验证码
		userInfo.setEmail("");//邮箱
		userInfo.setOpenId("");
		userInfo.setWechatNickName("");
		userInfo.setNickName(getNickName(phone));//昵称
		userInfo.setSex(-1);//性别       默认为-1
		userInfo.setHeadFrom(2);   //2.cos默认
		userInfo.setHeadImgUrl(MyConstant.DEFAULT_HEAD);  //默认头像
		String inviteCode = CommonUtils.getRandomString(6);
		userInfo.setInviteCode(inviteCode);//邀请码
		userInfo.setInviteQrCode(inviteCode);  //邀请二维码图片编码
		userInfo.setLastLoginTime(DateUtils.getNowDate());//最后登录时间
		userInfo.setIntegralNum(0);//积分数
		userInfo.setBalance(0);//余额
		userInfo.setContractedPlaceCardNum(0);//包场卡数量
		userInfo.setIsAnnualFeeVip("0");//是否是年费会员 0否 1是
		userInfo.setCreateUser(MyConstant.SYS_ADMIN);
		userInfo.setCreateTime(DateUtils.getNowDate());
		userInfo.setUpdateUser(MyConstant.SYS_ADMIN);
		userInfo.setUpdateTime(DateUtils.getNowDate());
		userInfo.setRoleId(1);
		
		userInfo.setIsFirstCharge(1);   //1 是首充资质
		userInfo.setIsRechargeLarge(0);;   //0 不是大额充值资质
		userInfo.setStatus(1);
		userInfo.setSharedByUserId(0);
		userInfo.setIsShared(-1);       //未被邀请
		userInfo.setSharedDate("");
		userInfo.setExperLevel(1);
		userInfo.setExperVal(0);
		userInfo.setExperName("初出茅庐");
		userInfo.setAge("");
		userInfo.setBirthday("");
		userInfo.setIsOnline(0);
		userInfo.setMemberType(1);
		userInfo.setVipStratDate(0);
		userInfo.setVipEndDate(0);
		userInfo.setDeviceType(-1);  //默认-1
		
		userMapper.insertUserInfo(userInfo);
		userInfo = userMapper.findBabyUserByPhone(phone);
		return userInfo;
	}

	
	
	/**
	 * 隐藏中间四位
	 * @param phone
	 * @return
	 */
	public String getNickName(String phone){
		return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
	}
	
	//查询用户合并信息
	public AgentUserCustom findCustomById(Integer userId) {
		return userMapper.findCustomById(userId);
	}

	public AgentUserCustom findCustomByPhoneNum(String phoneNum) {
		return userMapper.findCustomByPhoneNum(phoneNum);
	}

	public AgentUserCustom findByInviteCode(String inviteCode) {
		return userMapper.findByInviteCode(inviteCode);
	}
	
	/**
	 * cos删除原来图片，修改头像
	 * @param user
	 * @param head
	 * @return
	 * @throws Exception 
	 */
	public AgentUser updateHead(AgentUser user, MultipartFile head) throws Exception {
		String oldHead = user.getHeadImgUrl();
		if(!user.getHeadImgUrl().equals("https://mengmei-1256953255.cos.ap-guangzhou.myqcloud.com/defaultHead/default_head.jpg")){
			//cos自定义头像
			CosUtil.deleteFile(oldHead);
		}
		String newHead = CosUtil.uploadFile2Cos(head, "agentHead");
		user.setHeadImgUrl(newHead);
		return userInfoRepository.saveAndFlush(user);
	}

	public Integer findUserCountByPhone(String phoneNum) {
		return userMapper.findUserCountByPhone(phoneNum);
	}

	/**
	 * 查询是否绑定
	 * @param phoneNum
	 * @return
	 */
	public int findUserCountFromInviteUser(String phoneNum) {
		return userMapper.findUserCountFromInviteUser(phoneNum);
	}

	public UserInfo findBabyUserByPhone(String phoneNum) {
		return userMapper.findBabyUserByPhone(phoneNum);
	}

	public void updateBabyUser(UserInfo userInfo) {
		userMapper.updateBabyUser(userInfo.getUserId(),userInfo.getSecurityCode());
	}
}
